﻿using Coolzon.Common;
using Coolzon.UI.Common;
using Coolzon.UI.Common.Event.NCL;
using Coolzon.UI.Common.Event.Web;
using Coolzon.UI.Core.Views;
using Coolzon.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Coolzon.UI.ViewerApp.Views
{
    /// <summary>
    /// Interaction logic for SelectSolutionView.xaml
    /// 选择方案视图
    /// </summary>
    public partial class SelectSolutionView : View
    {
        private string _preSolutionName;
        public string SelectedSolutionName { get; private set; }

        /// <summary>
        /// 是否是切换方案
        /// </summary>
        private bool _isSwitchSolution;

        /// <summary>
        /// 是否是新建的控制域，在用户点击方案时会向服务器提出创建一个控制域的请求，
        /// 但是如果服务器上已经存在了控制域，那么不会创建信息的，此值为false，
        /// 如果创建了新的控制域，此值为true
        /// </summary>
        public bool IsNewDomain { get; private set; }

        public SelectSolutionView()
        {
            InitializeComponent();
            //Common.EventBus.Instance.Register(this);
            //Common.EventBus.Create(ClientProxyManager.EVENTBUS_FLAGNAME).Register(this);
            NCLEventBus.Register(this);
            WebEventBus.Register(this);

            SetFullScreenText();
        }

        public SelectSolutionView(string solutionName)
            : this()
        {
            _preSolutionName = solutionName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="currentSolutionName"></param>
        /// <param name="isSwitchSolution"></param>
        /// <param name="isCanBeBack"></param>
        public SelectSolutionView(string currentSolutionName, bool isSwitchSolution, bool isCanBeBack=true)
            : this()
        {
            _preSolutionName = currentSolutionName;
            _isSwitchSolution = isSwitchSolution;

            if (isCanBeBack)
            {
                _ctlBtnBack.Visibility = System.Windows.Visibility.Visible;
            }
        }

        #region override

        protected override void OnActive()
        {
            // 构造获取方案列表的请求
            WebEventBus.PublishAsync(new GetSolutionAlbumListBegin()
            {
                UserIdentity = UIContext.Current.UserIdentity
            });

            tbAccountName.Text = UIContext.Current.UserAccount;
            base.OnActive();
        }

        protected override void OnDeactive()
        {
            //Common.EventBus.Instance.Unregister(this);
            //Common.EventBus.Create(ClientProxyManager.EVENTBUS_FLAGNAME).Unregister(this);
            NCLEventBus.Unregister(this);
            WebEventBus.Unregister(this);

            base.OnDeactive();
        }

        #endregion

        private void OnBtnRetryClick(object sender, RoutedEventArgs e)
        {
            _ctlWrapPanel.Visibility = System.Windows.Visibility.Visible;
            _ctlPanelRetry.Visibility = System.Windows.Visibility.Hidden;
            // 构造获取方案列表的请求
            WebEventBus.PublishAsync(new GetSolutionAlbumListBegin()
            {
                UserIdentity = UIContext.Current.UserIdentity
            });
        }


        void btnSolution_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            SolutionAlbum solutionAlbum = (button.DataContext as SolutionAlbum);
            SelectedSolutionName = solutionAlbum.Name;
            this.Submit();
            //MessageBox.Show(SelectedSolutionName);
            //if (_isSwitchSolution)
            //{
            //    // 发送切换方案事件
            //    CPPEI.Coolzon.Event.NCL.NCLSwitchSolutionEvent @event = new CPPEI.Coolzon.Event.NCL.NCLSwitchSolutionEvent(SelectedSolutionName);
            //    CPPEI.Coolzon.Event.NCL.NCLEventBus.Publish(@event);
            //    this.Cancel();
            //}
            //else
            //{
            //    if (!UIContext.Current.IsAutoCreateDomain)
            //    {

            //        SelectDomainWindows selectDomain = new SelectDomainWindows(button.Tag as SolutionItem);
            //        selectDomain.Title = solutionItem.Caption;

            //        if (selectDomain.ShowDialog().Value)
            //        {
            //            this.Submit();
            //        }
            //    }
            //    else
            //    {
            //        // 构造创建控制域的请求
            //        Service.Contract.ReqCreateDomainData requestData = new Service.Contract.ReqCreateDomainData();
            //        requestData.SolutionCaption = solutionItem.Caption;
            //        requestData.SolutionName = solutionItem.Name;
            //        requestData.DomainCaption = "Auto";

            //        CPPEI.Coolzon.ServiceProxy.MainServiceRef.Request request = RequestUtil.BuildRequest(
            //            UIContext.Current.ControlDomainId,
            //            UIContext.Current.UserIdentity,
            //            Service.Contract.REQUEST_SCENARIO.CONNENT,
            //            Service.Contract.REQUEST_COMMAND.CONNECT.CREATEDOMAIN,
            //            Service.Contract.REQUEST_MODE.SELF,
            //            requestData);
            //        ClientProxyManager.Instance.SendRequestSys(request);
            //    }
            //}
        }

        //[Common.Subscribe]
        //public void OnReceiveCreateDomainData(Service.Contract.RespCreateDomainData data)
        //{
        //    if (data != null && data.IsSuccess)
        //    {
        //        UIContext.Current.ControlDomainId = data.DomainId;
        //        UIContext.Current.OperatorIdentity = data.OperatorIdentity;
        //        this.IsNewDomain = data.IsNewDomain;

        //        this.Dispatcher.Invoke(() =>
        //        {
        //            Common.EventBus.Create(ServiceProxy.ClientProxyManager.EVENTBUS_FLAGNAME).Unregister(this);
        //            this.Submit();
        //        });
        //    }
        //    else if (data != null)
        //    {
        //        MessageBox.Show(data.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        //    }
        //    else
        //    {
        //        MessageBox.Show("未知错误!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        //    }
        //}

        private void Logout_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            //LogoutView logoutView = new LogoutView();
            //UIContext.Current.RootViewContainer.PopView("注销", logoutView);
        }

        ///// <summary>
        ///// 收到来自服务器的注销结果
        ///// </summary>
        ///// <param name="event"></param>
        //[CPPEI.Coolzon.Common.Subscribe]
        //public void OnReceiveLogoutEvent(Service.Contract.RespLogoutData @event)
        //{
        //    this.Dispatcher.Invoke(() =>
        //    {
        //        Common.EventBus.Create(ServiceProxy.ClientProxyManager.EVENTBUS_FLAGNAME).Unregister(this);
        //        this.Cancel();
        //    });
        //}

        /// <summary>
        /// 全屏或是退出全屏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbFullscreen_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //UIEventBus.Publish(new UIChangeFullScreenStateEvent());
            if (UIContext.Current.IsFullScreen)
            {
                tbFullscreen.Text = "还原";
            }
            else
            {
                tbFullscreen.Text = "全屏";
            }
        }

        /// <summary>
        /// 设置文本为全屏或还原
        /// </summary>
        private void SetFullScreenText()
        {
            if (UIContext.Current.IsFullScreen)
            {
                tbFullscreen.Text = "还原";
            }
            else
            {
                tbFullscreen.Text = "全屏";
            }
        }

        private void _ctlBtnBack_Click_1(object sender, RoutedEventArgs e)
        {
            //UIEventBus.Publish(new UIHideSwitchSolutionViewEvent());
        }

        #region override 
        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
        {
            _ctlWrapPanel.Width = ((int)sizeInfo.NewSize.Width / 300) * 300;
            base.OnRenderSizeChanged(sizeInfo);
        }
        #endregion

        #region web events
        [Subscribe]
        public void OnReceiveGetSolutionAlbumListEnd(GetSolutionAlbumListEnd @event)
        {
            if(@event.State == WebEventState.Finished)
            {
                if (!string.IsNullOrEmpty(Config.Current.DefaultSolution))
                {
                    foreach (SolutionAlbum item in @event.SolutionAlbumList)
                    {
                        if (string.Equals(item.Name, Config.Current.DefaultSolution))
                        {
                            this.Dispatcher.Invoke(() =>
                            {
                                SelectedSolutionName = item.Name;
                                this.Submit();
                            });
                            return;
                        }
                    }
                }
                // 获取成功
                this.Dispatcher.Invoke(() =>
                {
                    _ctlWrapPanel.Visibility = System.Windows.Visibility.Visible;
                    _ctlPanelRetry.Visibility = System.Windows.Visibility.Hidden;

                    _ctlWrapPanel.Children.Clear();

                    foreach (SolutionAlbum item in @event.SolutionAlbumList)
                    {
                        if (!string.IsNullOrWhiteSpace(_preSolutionName) && _preSolutionName.Equals(item.Name))
                        {
                            continue;
                        }
                        Button btnSolution = new Button();
                        btnSolution.Width = 300;
                        btnSolution.Height = 240;
                        btnSolution.Style = (Style)Resources["btn-solution"];
                        btnSolution.Content = item.Name;
                        btnSolution.DataContext = item;
                        btnSolution.Click += btnSolution_Click;

                        _ctlWrapPanel.Children.Add(btnSolution);
                    }
                });
            }
            else
            {
                MessageBox.Show("获取方案列表失败");
                this.Dispatcher.Invoke(() =>
                {
                    // 获取失败
                    _ctlWrapPanel.Visibility = System.Windows.Visibility.Hidden;
                    _ctlPanelRetry.Visibility = System.Windows.Visibility.Visible;
                });
            }
        }
        #endregion
    }
}
